package com.softeem.god.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 添加使用UTF-8编码的StringHttpMessageConverter
        StringHttpMessageConverter stringConverter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
        List<MediaType> stringSupportedMediaTypes = new ArrayList<>();
        stringSupportedMediaTypes.add(new MediaType("text", "plain", StandardCharsets.UTF_8));
        stringSupportedMediaTypes.add(new MediaType("application", "json", StandardCharsets.UTF_8));
        stringConverter.setSupportedMediaTypes(stringSupportedMediaTypes);
        converters.add(stringConverter);
        
        // 配置Jackson消息转换器使用UTF-8编码
        MappingJackson2HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter();
        jacksonConverter.setDefaultCharset(StandardCharsets.UTF_8);
        List<MediaType> jacksonSupportedMediaTypes = new ArrayList<>();
        jacksonSupportedMediaTypes.add(new MediaType("application", "json", StandardCharsets.UTF_8));
        jacksonConverter.setSupportedMediaTypes(jacksonSupportedMediaTypes);
        
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        jacksonConverter.setObjectMapper(objectMapper);
        converters.add(jacksonConverter);
    }
}